<?php
namespace app\index\home;
use think\Controller;
use think\Db;
use EasyWeChat\Factory;
// use think\Session;
class Wechat extends Controller
{
    public $app;
    public function initialize()
    {
        $config = config('wechat.');

        $this->app = Factory::officialAccount($config);
    }
    /**
     * [check_serve 服务器校验响应]
     * @return [type] [description]
     */
    public function check_serve()
    {
        $response = $this->app->server->serve();
        // 将响应输出
        $response->send();exit;
    }

    public function getCode()
    {
        $oauth = $this->app->oauth;
        $data['data'] = $oauth->redirect();
        $data['code'] = true;
        $data['msg'] = 'ok';
        return json($data);
    }

    /**
     * [getAccessToken description]
     * @return [type] [description]
     */
    public function getAccessToken()
    {
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken(); // EasyWechat已经帮我们实现了accessToken的缓存问题，我们直接拿来用就行了
        return json($token);
    }
    /**
     * 获取单个用户的信息
     *
     * @param string $openId 用户openId
     * @return array
     */
    public function getUserInfo()
    {
        $openId = $this->request->get('openId');
        if (empty($openId)) return json(['code' => false, 'msg' => 'openId must be set']);
        $userInfo = $this->app->user->get($openId);
        return json($userInfo);
    }



    /**
     * [oauth_callback 回调函数]
     * @return [type] [description]
     */
    public function oauth_callback()
    {
        $config = config('wechat.');
        $code = $this->request->param('code');
        $get_token_url =  'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$config['app_id'].'&secret='.$config['secret'].'&code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $res = curl_exec($ch);
        if ($err = curl_errno($ch)) {
        	  var_dump($err);die;
        }
        curl_close($ch);
        // if(!$res){
        // 	return false;
        // }
        $json_obj = json_decode($res,true);
		
        //根据openid和access_token查询用户信息
        $access_token = $json_obj['access_token'];
        $openid = $json_obj['openid'];

        $find = Db::name('user_auths')->where('identity_type','official_accounts')->where('identifier',$openid)->find();
        if($find){
            $userInfo = Db::name('users')->where('id',$find['user_id'])->find();
            $array = [
                'token'=>getToken($find['user_id']),
                'user_name'=>$userInfo['nickname'],
                'user_avatar'=> $this->request->domain().$userInfo['avatar'],
            ];
            // return $array;
            header('Location:'.$this->request->domain().'/wap/#/pages/home/weixin?'.http_build_query($array));die;
        }
        $get_user_info_url =  'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

        $ch2 = curl_init();
        curl_setopt($ch2,CURLOPT_URL,$get_user_info_url);
        curl_setopt($ch2,CURLOPT_HEADER,0);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch2, CURLOPT_CONNECTTIMEOUT, 10);
        $res2 = curl_exec($ch2);
        curl_close($ch2);
        $user_obj = json_decode($res2,true);
        $userInfo = $this->addUser($user_obj);
        if($userInfo == false){
            header('Location:'.$this->request->domain().'/wap/#/pages/home/login');die;
        }
        header('Location:'.$this->request->domain().'/wap/#/pages/home/weixin?'.http_build_query($userInfo));die;
    }
    protected function addUser($userInfo=[])
    {
        if(empty($userInfo)){
            return false;
        }
        Db::startTrans();
        try {
            $content = getimage($userInfo['headimgurl'],'./upload/headimg/',$userInfo['openid'].'.jpg',1);
            $model = Db::name('users');

            $insert_data = [
                'nickname' => $userInfo['nickname'],
                'avatar'   => $content['error'] == 0 ? $content['save_path'] : '/static/images/avatar.png',
                'user_type'=> 0,
                'createtime'=> date('Y-m-d H:i:s',time())
            ];
            $insertId = $model->insertGetId($insert_data);
            if($insertId > 0){
                $auth_data = [
                    'user_id' => $insertId,
                    'identity_type' => 'official_accounts',
                    'identifier'    => $userInfo['openid'],
                    'credential'    => '',
                    'login_num'     => 1
                ];

                Db::name('user_auths')->insert($auth_data);
            }else{
                throw new Exception("添加失败", 1);

            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
            // return $this->error($e->getMessage());
        }

        $array = [
            'token'=>getToken($insertId),
            'user_name'=>$userInfo['nickname'],
            'user_avatar'=> $this->request->domain().$insert_data['avatar'],
        ];
        return $array;
    }

    
}
